<script lang="ts" setup>
import { getBuyNowPreOrderAPI, getPreOrderAPI, postPreOrderAPI, getBuyAgainPreOrderByIdAPI } from '@/apis/order';
import { useAddressStore } from '@/stores/modules/addressStore';
import { OrderPreResult } from '@/types/order';
import { onShow } from '@dcloudio/uni-app';
import { PickerViewOnChange } from '@uni-helper/uni-app-types';
import { computed, ref } from 'vue';

const { safeAreaInsets } = uni.getSystemInfoSync();

// 获取路由参数
const props = defineProps<{
  skuId?: string,
  count?: string,
  orderId?: string,
  addressId?: string,
}>();

const addressStore = useAddressStore();

// 预付订单信息
const orderPreResult = ref<OrderPreResult>();
const getOrderPreResult = async () => {
  let response;
  if (props.skuId && props.count) {
    // 立刻购买预支付订单
    response = await getBuyNowPreOrderAPI({ skuId: props.skuId, count: props.count, addressId: props.addressId }).request;
  } else if (props.orderId) {
    // 再次购买预支付订单
    response = await getBuyAgainPreOrderByIdAPI(props.orderId).request;
  } else {
    response = await getPreOrderAPI().request;
  }
  orderPreResult.value = response.result;
};

// 选中地址信息
const address = computed(() => addressStore.selectedAddress || orderPreResult.value?.userAddresses.find(a => a.id === props.addressId));

onShow(() => {
  getOrderPreResult();
});

// 配送时间
const deliveryDate = [
  { type: 1, text: '时间不限（周一至周日）' },
  { type: 2, text: '工作日配送（周一至周五）' },
  { type: 3, text: '周末配送（周六至周日）' },
];

// 当前选中的配送时间
const selectedDeliveryDateIndex = ref(0);

// 切换配送时间事件
const onSelectedDeliveryDateChange: PickerViewOnChange = e => selectedDeliveryDateIndex.value = e.detail.value as unknown as number;

// 订单备注
const buyerMessage = ref('');

// 订单预支付提交
const onOrderPreSubmit = async () => {
  // 检查地址
  if (!address.value) return uni.showToast({ icon: 'none', title: '请选择收货地址！' });
  // 发送请求
  const response = await postPreOrderAPI({
    addressId: address.value.id,
    buyerMessage: buyerMessage.value,
    deliveryTimeType: deliveryDate[selectedDeliveryDateIndex.value].type,
    goods: orderPreResult.value!.goods.map(({ count, skuId }) => ({ count, skuId })),
    payChannel: 2,
    payType: 1,
  }).request;
  // 重定向到订单详情页面
  uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${response.result.id}` });
};
</script>

<template>
  <view class="viewport">
    <scroll-view scroll-y class="viewport">
      <!-- 收货地址 -->
      <navigator class="shipment" hover-class="none" url="/pagesMember/address/address?from=order">
        <view class="user">{{ address?.receiver }} {{ address?.contact }}</view>
        <view class="address">{{ address?.fullLocation || '请选择收货地址' }}</view>
        <text class="icon icon-right" />
      </navigator>
      <!-- 商品信息 -->
      <view class="goods">
        <navigator v-for="item in orderPreResult?.goods" :key="item.id" class="item"
          :url="`/pages/good/good?id=${item.id}`" hover-class="none">
          <image class="picture" :src="item.picture" />
          <view class="meta">
            <view class="name ellipsis">{{ item.name }}</view>
            <view class="attrs">{{ item.attrsText }}</view>
            <view class="prices symbol">{{ item.price }}</view>
          </view>
          <view class="count">{{ item.count }}</view>
        </navigator>
      </view>
      <!-- 配送与支付 -->
      <view class="related">
        <view class="item">
          <text class="text">配送时间</text>
          <picker mode="selector" :range="deliveryDate" range-key="text" @change="onSelectedDeliveryDateChange">
            <view class="icon-fonts picker">{{ deliveryDate[selectedDeliveryDateIndex].text }}</view>
          </picker>
        </view>
        <view class="item">
          <text class="text">订单备注</text>
          <input class="input" v-model="buyerMessage" :cursor-spacing="30" placeholder="请填写订单备注，建议事先与商家沟通好" />
        </view>
      </view>
      <!-- 支付 -->
      <view class="settlement">
        <view class="item">
          <text class="text">商品总价：</text>
          <text class="number symbol">{{ orderPreResult?.summary.totalPrice }}</text>
        </view>
        <view class="item">
          <text class="text">运费：</text>
          <text class="number symbol">{{ orderPreResult?.summary.postFee }}</text>
        </view>
      </view>
    </scroll-view>
    <!-- 吸底工具栏 -->
    <view class="toolbar" :style="{ paddingBottom: `${safeAreaInsets?.bottom}px` }">
      <view class="total-pay symbol">
        <text class="number">{{ orderPreResult?.summary.totalPayPrice }}</text>
      </view>
      <view class="button" :class="{ disabled: !orderPreResult || !address }" @tap="onOrderPreSubmit">提交订单</view>
    </view>
  </view>
</template>

<style lang="scss">
.viewport {
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
  display: flex;
  flex-direction: column;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png) 20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #27ba9b;
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>